package com.ilas.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.ilas.config.DynamicDataSource;
import com.ilas.dao.TenantInfoDao;
import com.ilas.entity.TenantInfo;
import com.ilas.service.ITenantInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>${Description}</p>
 *
 * @author luzck
 * @date 2021/4/1 16:43
 */
@Service
public class TenantInfoServiceImpl implements ITenantInfoService {

    @Resource
    private TenantInfoDao tenantInfoDao;

    @Override
    public List<TenantInfo> findList() {
        return tenantInfoDao.findList();
    }

    @Override
    public TenantInfo add(TenantInfo tenantInfo) {
        int i = tenantInfoDao.insert(tenantInfo);
        if (i > 0) {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(tenantInfo.getDataSourceDriver());
            dataSource.setUrl(tenantInfo.getDataSourceUrl());
            dataSource.setUsername(tenantInfo.getDataSourceUsername());
            dataSource.setPassword(tenantInfo.getDataSourcePassword());

            Map<Object, Object> map = new HashMap<>();

            map.put(tenantInfo.getTenantId(), dataSource);
            DynamicDataSource dynamicDataSource = new DynamicDataSource();
            //设置数据源
            dynamicDataSource.setTargetDataSources(map);
            //必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
            dynamicDataSource.afterPropertiesSet();

            return tenantInfo;
        }
        return null;
    }
}
